<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/5/7
 * Time: 15:54
 * 购物车模块
 */
namespace app\home\model;

use app\home\model\Base;
use think\Model;
use think\Request;
use think\Db;
use think\Exception;
use think\Log;

class Shop extends Base {

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取卡片套餐列表
     * 默认显示15条数据
     * @return array ['package'=>套餐列表数组,'param'=>请求参数,'search'=>拼接的地址参数]
     */
    public function getShopListM()
    {
        try {
            $param = Request::instance()->param();
            $search = '';   // 拼接搜索条件，返回
            $where['aid'] = ['eq',$this->user_info['agent_id']];   // 代理商id
            $where['pkg_status'] = ['eq','1'];   // 套餐状态
            $globalsimtype = isset($param['globalsimtype']) ? trim($param['globalsimtype']) : '';
            if($globalsimtype != ''){   // 运营商
                $where['operator_type'] = ['eq',$globalsimtype];
                $search .= '&globalsimtype='.$globalsimtype;
            }
            $total = isset($param['total']) ? trim($param['total']) : '';
            if($total){   // 规格
                $where['total'] = [['eq',$total.'M'],['eq',$total.'G'],'or'];
                $search .= '&total='.$total;
            }
            $list = Db::name('pkg')
                ->field('id,operator_type,pkg_kind,total,yunchi_price,agent_price')
                ->where($where)
                ->order('operator_type asc, pkg_kind asc,id desc')
                ->paginate(15,false);
            $package = $list->toArray();
            if(!$package['data']){
                return ['package'=>$package,'param'=>$param,'search'=>$search];
            }
            foreach($package['data'] as &$value){   // 处理数据
                $value['pkg_kind'] = $this->package_type[$value['pkg_kind']];
                $value['pkg_price'] = $this->getPackagePrice($value, $this->user_info);
                $value['icon'] = $this->icon[$value['operator_type']];
            }
            return ['package'=>$package,'param'=>$param,'search'=>$search];
        } catch (Exception $e) {
            Log::write('获取套餐列表异常：'.$e->getMessage(),'error');
        }
    }
    
    /**
     * 获取套餐详情
     * @param int $pid 套餐id
     * @param int $sid 材质规格id
     * @return array 套餐详情信息
     */
    public function getPackageDetailsM($pid = 0,$sid = 0)
    {
        try {
            $param = Request::instance()->param();
            $param['id'] = isset($param['id']) ? $param['id'] : $pid;
            $sql = "SELECT * FROM yc_pkg WHERE `id` = ".$param['id']." AND `aid` = ".$this->user_info['agent_id']." AND `pkg_status` = 1 LIMIT 1";
            $result = Db::query($sql);
            if(!$result){
                return false;
            }
            // 获取套餐真实价格
            $result[0]['pkg_price'] = $this->getPackagePrice($result[0], $this->user_info);
            // 获取材质规格
            $sid = $sid ? $sid : $result[0]['sid'];
            $result[0]['material'] = $this->getCardMaterial($sid);
            $result[0]['operator_type'] = '中国'.$this->globalsimtype[$result[0]['operator_type']];
            $result[0]['pkg_kind_text'] = $this->package_type[$result[0]['pkg_kind']];
            $result[0]['text'] = explode("\n",$result[0]['text']);   // 处理文字说明
            if (!preg_match('/(http:\/\/)|(https:\/\/)/i', $result[0]['card_img'])) {   // 图片地址不是全路径，补全
                $result[0]['card_img'] = 'http://iot.yunchiiot.com'.$result[0]['card_img'];   // 图片绝对地址
            }
            return $result[0];
        } catch (Exception $e) {
            Log::write('获取套餐详情异常：'.$e->getMessage(),'error');
        }
    }
    
    /**
     * 加入购物车，相同条件的更新购卡数量，反之新增记录
     * @return array 其中的new_cart是根据购物车是新增还是改变原有数据决定购物车的总量
     */
    public function addToCartM()
    {
        try {
            $param = Request::instance()->post();
            // 验证套餐是否存在及类型
            $check_package = $this->getPackageDetailsM();
            if(!$check_package){
                return ['code'=>1,'msg'=>'加入购物车失败！'];
            }
            // 验证材质规格
            $check_material = $this->getCardMaterial($param['material']);
            if(!$check_material[0]){
                return ['code'=>2,'msg'=>'请选择卡片的材质规格！'];
            }
            // 验证卡片类型
            if(!in_array($param['type'],[1,2])){
                return ['code'=>3,'msg'=>'请选择卡片的类型！'];
            }
            $check_number = "/^[1-9]\d*$/";   // 验证是否为整数
            // 验证订购周期
            $param['cycle'] = isset($param['cycle']) ? $param['cycle'] : 1;  // 默认订购周期 1
            if($check_package['pkg_kind'] == '0' && ( $param['cycle'] < 3 || !preg_match($check_number,$param['cycle']))){
                return ['code'=>4,'msg'=>'月套餐的最小订购周期为3个月！'];
            }
            // 验证购卡数量
            if($param['number'] < 1 || !preg_match($check_number,$param['number'])){
                return ['code'=>5,'msg'=>'卡片订购数量至少一张！'];
            }
            // 相同套餐相同配置的购卡数量增加
            $where = " `user_type` = 2 AND `uid` =  ".$this->user_info['id']." AND `pid` = ".$param['id']." AND `sid` = ".$param['material']." AND `card_type` = ".$param['type']." AND `cycle` = ".$param['cycle'];
            $selec_sql = "SELECT id FROM yc_cart WHERE ".$where;
            $select = Db::query($selec_sql);
            if($select){   // 增加购卡数量
                $update_sql = "UPDATE yc_cart SET `number` = number + ".$param['number']." WHERE `id` = ".$select[0]['id'];
                $update = Db::execute($update_sql);
                if(!$update){
                    return ['code'=>6,'msg'=>'加入购物车失败！'];
                }
                return ['code'=>0,'msg'=>'加入购物车成功！','new_cart'=>0];
            }
            // 购物车新增
            $values = "'2',".$this->user_info['id'].",".$param['id'].",".$param['material'].",".$param['type'].",".$param['cycle'].",".$param['number'].",".time();
            $add_sql = "INSERT INTO yc_cart (`user_type`,`uid`,`pid`,`sid`,`card_type`,`cycle`,`number`,`addtime`) VALUES (".$values.")";
            $add = Db::execute($add_sql);
            if(!$add){
                return ['code'=>7,'msg'=>'加入购物车失败！'];
            }
            return ['code'=>0,'msg'=>'加入购物车成功！','new_cart'=>1];
        } catch (Exception $e) {
            Log::write('加入购物车异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取购物车列表
     * 当前用户、套餐发布状态的购物车记录
     */
    public function getCartListM()
    {
        try {
            $sql = "SELECT `id`,`pid`,`sid`,`card_type`,`cycle`,`number` FROM yc_cart WHERE `user_type` = 2 AND `uid` = ".$this->user_info['id'];
            $cart = Db::query($sql);
            $total_price = 0;   // 合计金额
            $total_number = 0;  // 总卡量
            $id_string = '';  // 购物车记录id组成的字符串
            if(!$cart){
                return ['cart'=>[],'total_price'=>$total_price];
            }
            foreach($cart as $key=>&$value){
                $package = $this->getPackageDetailsM($value['pid'],$value['sid']);   // 获取套餐信息
                if(!$package){    // 查询不到套餐信息，删除该条购物车数据
                    unset($cart[$key]);
                    continue;
                }
                $value['pkg_price'] = $package['pkg_price'];
                $value['total'] = $package['total'];
                $value['operator_type'] = $package['operator_type'];
                $value['pkg_kind'] = $package['pkg_kind_text'];
                $value['material'] = $package['material'][0]['specification'];
                $value['material_price'] = $package['material'][0]['price'];
                $value['card_type'] = $this->card_type[$value['card_type']];
                $value['small_plan'] = ($value['pkg_price']*$value['cycle'] + $value['material_price'])*$value['number'];
                // 总价
                $total_price += $value['small_plan'];
                // 总卡量
                $total_number += $value['number'];
                $id_string .= $value['id'].',';
            }
            $id_string = rtrim($id_string,',');
            return ['cart'=>$cart,'total_price'=>$total_price,'total_number'=>$total_number,'id_string'=>$id_string];
        } catch (Exception $e) {
            Log::write('获取购物车列表异常：'.$e->getMessage(),'error');
        }
    }
    
    /**
     * 删除购物车数据
     * @param string $cid 购物车id (1,2)
     * @return array 删除结果
     */
    public function deleteCartM($cid = '0')
    {
        try {
            $param = Request::instance()->post();
            $param['id'] = isset($param['id']) ? $param['id'] : $cid ;
            if(!$param['id']){
                return ['code'=>1,'msg'=>'请选择要删除的数据！'];
            }
            $sql = "DELETE FROM yc_cart WHERE `user_type` = 2 AND `uid` = ".$this->user_info['id']." AND `id` in (".$param['id'].")";
            $result = Db::execute($sql);
            if(!$result){
                return ['code'=>2,'msg'=>'数据删除失败！'];
            }
            return ['code'=>0,'msg'=>'数据删除成功！'];
        } catch (Exception $e) {
           Log::write('删除购物车异常：'.$e->getMessage(),'error');
        }
    }
    
    /**
     * 获取用户的收货地址列表
     * @param int $aid 收货地址id
     * @return array 收货地址数组
     */
    public function getReceivingAddressM($aid = 0)
    {
        try {
            $where = " `user_type` = 3 AND `user_id` = ".$this->user_info['id'];
            if($aid){
                $where .= " AND `id` = ".$aid;
            }
            $sql = "SELECT `id`,`name`,`phone`,`province`,`city`,`area`,`address` FROM yc_address WHERE ".$where." ORDER BY `status` ASC,`id` DESC";
            $address = Db::query($sql);
            if(!$address){
                return $address;
            }
            foreach($address as &$value){
                $province = $this->getProvince($value['province']);  // 获取省份信息
                $value['province_text'] = $province['province'];
                $city = $this->getCity($value['city']);  // 获取城市信息
                $value['city_text'] = $city['city'];
                $area = $this->getArea($value['area']);  // 获取区域信息
                $value['area_text'] = $area['area'];
            }
            return $address;
        } catch (Exception $e) {
            Log::write('获取用户收货地址异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取快递列表
     * @param int $province 省份id
     * @param int $express 快递id
     * @return array 快递列表
     */
    public function getExpressListM($province = 0,$express = 0)
    {
        try {
            $param = Request::instance()->post();
            $province = $province ? $province : $param['p'];
            $where = "`user_type` = 2 AND `user_id` = ".$this->user_info['agent_id']." AND `status` = 1 AND `province` = ".$province;
            if($express){
                $where .= " AND `id` = ".$express;
            }
            $sql = "SELECT `id`,`price`,`express_name` FROM yc_express WHERE ".$where;
            $express = Db::query($sql);
            return $express;
        } catch (Exception $e) {
            Log::write('获取快递列表异常：'.$e->getMessage(),'error');
        }
    }
    
    /**
     * 创建订单
     */
    public function submitOrderM()
    {
        try {
            $param = Request::instance()->post();
            // 验证收货地址
            $check_address = $this->getReceivingAddressM($param['address']);
            if(!$check_address){
                return ['code'=>1,'msg'=>'请选择收货地址'];
            }
            // 验证快递信息
            $check_express = $this->getExpressListM($check_address[0]['province'],$param['express']);
            if(!$check_express){
                return ['code'=>2,'msg'=>'请选择配送方式'];
            }
            // 获取购物车信息
            $cart = $this->getCartListM();
            if(!$cart['total_number']){
                return ['code'=>3,'msg'=>'创建订单失败'];
            }
            $order_info['address'] = [   // 地址信息
                'phone'=>$check_address[0]['phone'],
                'name'=>$check_address[0]['name'],
                'province'=>$check_address[0]['province_text'],
                'city'=>$check_address[0]['city_text'],
                'area'=>$check_address[0]['area_text'],
                'address'=>$check_address[0]['address'],
            ];
            // 生成订单
            foreach($cart['cart'] as $key=>$value){
                $order_info['card'][$key] = [
                    'pid'=>$value['pid'],   // 套餐id
                    'price'=>$value['pkg_price'],   // 套餐价格
                    'guige'=>$value['material'],   // 卡片材质规格
                    'gg_price'=>$value['material_price'],   // 单张卡费
                    'card_type'=>$value['card_type'],   // 卡片类型
                    'cycle'=>$value['cycle'],   // 购卡周期
                    'number'=>$value['number'],   // 购卡数量
                    'operator'=>$value['operator_type'],   // 运营商
                    'pkg_kind'=>$value['pkg_kind'],   // 套餐类型
                    'total'=>$value['total'],   // 套餐总量
                    'small_plan'=>$value['small_plan'],   // 小计
                ];
            }
            $check_express[0]['price'] = $check_express[0]['price']*100;
            $order_money = $cart['total_price']*100 + $check_express[0]['price'];
            if($cart['total_price'] >= 60000){   // 满600免运费
                $check_express[0]['price'] = 0;
            }
            $create_order = $this->createOrder($order_money, '11', 4, json_encode($order_info,JSON_UNESCAPED_UNICODE), 2, $param['remarks'], $check_express[0]);
            if(!$create_order){
                return ['code'=>4,'msg'=>'创建订单失败'];
            }
            // 删除购物车数据
            $delete_cart = $this->deleteCartM($cart['id_string']);
            return ['code'=>0,'msg'=>'创建订单成功','order_number'=>$create_order];
        } catch (Exception $e) {
            Log::write('创建订单异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取所属套餐的卡片的材质规格
     * @param string $sid 材质规格id，多个用逗号隔开
     * @return array ['0'=>材质规格参数,'1'=>材质规格参数,.....];
     */
    protected function getCardMaterial($sid = '')
    {
        try {
            if(!$sid){
                return false;
            }
            $sql = "SELECT `id`,`price`,`specification` FROM yc_specification WHERE id in (".$sid.")";
            $material = Db::query($sql);
            return $material;
        } catch (Exception $e) {
            Log::write('获取套餐的材质规格异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取指定省份的信息
     * @param int $pid 省份id
     * @return array 省份信息
     */
    protected function getProvince($pid = 0)
    {
        try {
            $sql = "SELECT `id`,`provinceid`,`province` FROM yc_provinces WHERE `id` = ".$pid;
            $result = Db::query($sql);
            return $result[0];
        } catch (Exception $e) {
            Log::write('获取省份信息异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取指定城市的信息
     * @param int $cid 城市id
     * @return array 城市信息
     */
    protected function getCity($cid = 0)
    {
        try {
            $sql = "SELECT `id`,`cityid`,`city`,`provinceid` FROM yc_cities WHERE `id` = ".$cid;
            $result = Db::query($sql);
            if(in_array($result[0]['city'],['市辖区','县'])){   // 过滤信息
                $result[0]['city'] = '';
            }
            return $result[0];
        } catch (Exception $e) {
            Log::write('获取城市信息异常：'.$e->getMessage(),'error');
        }
    }

    /**
     * 获取指定市区的信息
     * @param int $aid 区域id
     * @return array 区域信息
     */
    protected function getArea($aid = 0)
    {
        try {
            $sql = "SELECT `id`,`areaid`,`area`,`cityid` FROM yc_areas WHERE `id` = ".$aid;
            $result = Db::query($sql);
            return $result[0];
        } catch (Exception $e) {
            Log::write('获取区域信息异常：'.$e->getMessage(),'error');
        }
    }

}